﻿using _2._18._2015_MoviesInClass.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace _2._18._2015_MoviesInClass.Adapters
{
    public class MovieFBAdapter : IMovieAdapter
    {
        private string _moviesUrl = "https://nicksmovies2.firebaseio.com/movies.json";

        public List<MovieViewModel> GetMovies(string userId = null)
        {
            List<MovieViewModel> models = new List<MovieViewModel>();

            WebClient client = new WebClient();
            var result = client.DownloadString(_moviesUrl);

            IDictionary<string, object> fbObj = JsonConvert.DeserializeObject<ExpandoObject>(result, new ExpandoObjectConverter());

            foreach (dynamic m in fbObj.Values)
            {
                models.Add(new MovieViewModel
                {
                    MovieId = (int)m.MovieId,
                    PosterUrl = m.PosterUrl,
                    Rating = (int)m.Rating,
                    Title = m.Title
                });
            }
            return models;
        }

        public void CreateMovie(MovieViewModel model, string userId)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_moviesUrl);
            request.Method = "POST";

            var jsonObj = new
            {
                MovieId = model.MovieId,
                Title = model.Title,
                PosterUrl = model.PosterUrl,
                Rating = model.Rating,
                UserId = userId
            };

            byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jsonObj));

            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //WebResponse response = request.GetResponse();
            //dataStream = response.GetResponseStream();
            //StreamReader reader = new StreamReader(dataStream);
            //string responseFromServer = reader.ReadToEnd();            
        }

        public MovieViewModel GetMovie(int movieId)
        {
            throw new NotImplementedException();
        }

        public void UpdateMovie(MovieViewModel model)
        {
            throw new NotImplementedException();
        }
    }
}